from typing import List, Optional
from sqlalchemy.orm import Session

from models.SubmitInfo import SubmitInfo
from schemas.Submitinfo import SubmitInfoCreate, SubmitInfoUpdate

class SubmitInfoServe:
    @staticmethod
    def create(db: Session, submitinfo: SubmitInfoCreate) -> SubmitInfo:
        db_obj = SubmitInfo(**submitinfo.dict())
        db_obj.ids = str(db_obj.ids)
        db.add(db_obj)
        db.commit()
        db.refresh(db_obj)
        return db_obj

    @staticmethod
    def get_by_id(db: Session, id: int) -> Optional[SubmitInfo]:
        return db.query(SubmitInfo).filter(SubmitInfo.id == id, SubmitInfo.isDelete != 1).first()

    @staticmethod
    def get_all(db: Session, skip: int = 0, limit: int = 100) -> List[SubmitInfo]:
        return db.query(SubmitInfo).filter(SubmitInfo.isDelete != 1).offset(skip).limit(limit).all()

    @staticmethod
    def update(db: Session, id: int, submitinfo_update: SubmitInfoUpdate) -> Optional[SubmitInfo]:
        db_obj = db.query(SubmitInfo).filter(SubmitInfo.id == id, SubmitInfo.isDelete != 1).first()
        if not db_obj:
            return None
        update_data = submitinfo_update.dict(exclude_unset=True)
        for key, value in update_data.items():
            setattr(db_obj, key, value)
        db.commit()
        db.refresh(db_obj)
        return db_obj

    @staticmethod
    def delete(db: Session, id: int) -> bool:
        db_obj = db.query(SubmitInfo).filter(SubmitInfo.id == id, SubmitInfo.isDelete != 1).first()
        if not db_obj:
            return False
        db_obj.isDelete = 1
        db.commit()
        return True